package com.tuanzi.loan.business.repository.system.impl;

import static com.tuanzi.loan.generated.jooq.loan.tables.LoanFunctionalPermission.LOAN_FUNCTIONAL_PERMISSION;
import static com.tuanzi.loan.generated.jooq.loan.tables.LoanFunctionalPermissionRelation.LOAN_FUNCTIONAL_PERMISSION_RELATION;
import static com.tuanzi.loan.generated.jooq.loan.tables.LoanRole.LOAN_ROLE;
import static com.tuanzi.loan.generated.jooq.loan.tables.LoanUserRole.LOAN_USER_ROLE;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.jooq.Select;
import org.jooq.impl.TableImpl;
import org.springframework.stereotype.Repository;

import com.tuanzi.loan.business.entity.system.FunctionalPermission;
import com.tuanzi.loan.business.entity.system.RelationType;
import com.tuanzi.loan.business.repository.system.custom.FunctionalPermissionRepositoryCustom;
import com.tuanzi.loan.core.repository.JOOQBaseRepository;

/**
 * @author Ray 2017/09/21
 */
@Repository
@SuppressWarnings({ "rawtypes", "unchecked" })
public class FunctionalPermissionRepositoryImpl extends JOOQBaseRepository implements FunctionalPermissionRepositoryCustom {

	@PersistenceContext
	private EntityManager entityManager;

	@Override
	protected TableImpl getTable() {
		return LOAN_FUNCTIONAL_PERMISSION;
	}

	@Override
	public List<FunctionalPermission> findAllPermissionByUserId(String userId) {

		Select selectByUser = dslContext.select(LOAN_FUNCTIONAL_PERMISSION.fields()).from(LOAN_FUNCTIONAL_PERMISSION).innerJoin(LOAN_FUNCTIONAL_PERMISSION_RELATION)
				.on(LOAN_FUNCTIONAL_PERMISSION.ID.eq(LOAN_FUNCTIONAL_PERMISSION_RELATION.PERMISSION_ID))
				.where(LOAN_FUNCTIONAL_PERMISSION_RELATION.RELATION_TYPE.eq((byte) RelationType.USER.ordinal())).and(LOAN_FUNCTIONAL_PERMISSION_RELATION.RELATION_ID.eq(userId))
				.and(LOAN_FUNCTIONAL_PERMISSION.ENABLE);

		Select subQueryRole = dslContext.select(LOAN_ROLE.ID).from(LOAN_ROLE).innerJoin(LOAN_USER_ROLE)
				.on(LOAN_ROLE.ID.eq(LOAN_USER_ROLE.ROLE_ID).and(LOAN_USER_ROLE.USER_ID.eq(userId))).and(LOAN_ROLE.ENABLE);

		Select selectByUserRole = dslContext.select(LOAN_FUNCTIONAL_PERMISSION.fields()).from(LOAN_FUNCTIONAL_PERMISSION).innerJoin(LOAN_FUNCTIONAL_PERMISSION_RELATION)
				.on(LOAN_FUNCTIONAL_PERMISSION.ID.eq(LOAN_FUNCTIONAL_PERMISSION_RELATION.PERMISSION_ID))
				.where(LOAN_FUNCTIONAL_PERMISSION_RELATION.RELATION_TYPE.eq((byte) RelationType.ROLE.ordinal()))
				.and(LOAN_FUNCTIONAL_PERMISSION_RELATION.RELATION_ID.in(subQueryRole)).and(LOAN_FUNCTIONAL_PERMISSION.ENABLE);

		return selectByUser.union(selectByUserRole).fetch().into(FunctionalPermission.class);
	}
}
